package com.xiaojiezhu.netty.base.protocol;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

/**
 * 作者 zxj<br>
 * 时间 2017/7/14 16:11
 * 说明 协议头
 */
public class CobraProtocolHeader {
    /**
     * 默认的contentType,是传递字符串
     */
    public final static String DEFAULT_CONTENT_TYPE = "STRING";
    /**
     * content-type占多少个字节
     */
    public final static int CONTENT_TYPE_LENGTH = 256;
    /**
     * 协议版本号
     */
    private int version;
    /**
     * 协议内容的长度
     */
    private int contentLength;
    /**
     * 请求的内容，根据这个内容，寻找不同的处理器处理
     */
    private String contentType;



    public int getVersion() {
        return version;
    }

    public void setVersion(int version) {
        this.version = version;
    }

    public int getContentLength() {
        return contentLength;
    }

    public void setContentLength(int contentLength) {
        this.contentLength = contentLength;
    }

    public String getContentType() {
        return contentType;
    }

    public void setContentType(String contentType) {
        if(contentType == null){
            this.contentType = DEFAULT_CONTENT_TYPE;
        }
        try {
            if(contentType.getBytes("UTF-8").length > CONTENT_TYPE_LENGTH){
                throw new IndexOutOfBoundsException("cobra协议的contentType不能超出" + CONTENT_TYPE_LENGTH + "个字节");
            }
            ByteBuffer buffer = ByteBuffer.allocate(CONTENT_TYPE_LENGTH);
            buffer.put(contentType.getBytes("UTF-8"));
            byte[] array = buffer.array();
            contentType = new String(array);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        this.contentType = contentType;
    }



    @Override
    public String toString() {
        return "CobraProtocolHeader{" +
                "version=" + version +
                ", contentLength=" + contentLength +
                ", contentType='" + contentType + '\'' +
                '}';
    }
}
